// pages/caseDescribe/caseDescribe.js
import request from '../../utils/config.js';
import util from '../../utils/util.js';
let WXBizDataCrypt = require('../../utils/RdWXBizDataCrypt.js');
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // isFile: false,
    windowHeight: wx.getSystemInfoSync().windowHeight - 91,
    caseInfoData: "",
    proDataList: "",
    lastLength: 0,
    firstLength: 0,
    isToastBg: false,
    isToast: false,
    wordDesShow: false,//文字描述
    serDes: "",//服务描述
    preventStatus: true,
    weatherEval: true,//是否评价过
    serviceAtt: [],
    responseAtt: [],
    specialtyAtt: [],
    serviceAttFlag: "",
    responseAttFlag: "",
    specialtyAttFlag: "",
    currentNum: 0,
    newFileList: new Array(),
    ifLJPJ: false,
    caseId:"",
    checkDiv:true,
    dimNum:2,
    isFocus:false,
    inputValue: '',
    codes: ["", "", "", ""],
    nickName:"",
    validCodeCheck:false,
    showModel:false,
    animationM: {},
    animationS: {},
    isAlredyLoad: false,//打开文档返回后页面不要刷新
    showMoreBtn: false,
    showMoreTrick: false,
  },
  /**
     * 点击输入框
     */
  openKeyboard: function () {
    this.setData({
      isFocus: true
    })
  },

  //获取监听手机号
  getPhoneNum: function(e){
    console.log('输入手机号后四位===',e.detail.value)
    var text = e.detail.value;
    var textLength = text.length;
    var codeArray = new Array();
    for (var i = 0; i < (textLength > 4 ? 4 : textLength); i++) {
      var code = text.substr(i, 1);
      codeArray[i] = (code);
    }
    for (var i = codeArray.length; i < 4; i++) {
      codeArray.push("");
    }
    this.setData({
      codes: codeArray
    })
    if (textLength > 3) {
      var returnString = text.substr(0, 4);
      this.judgePhoneNum(returnString);
    }
  },

  //开始调接口验证
  judgePhoneNum: function(num){
    let headerInfo = {
      pageNum: "",
      pageSize: "",
      sessionId: app.globalData.sessionId
    }
    let bodyInfo = {
      caseId: this.data.caseId,
      mobileNo: num
    }
    let _this = this;
    request.requestLogin_api("invitedVerifyUser", headerInfo, bodyInfo, (obj) => {
      console.log("验证手机号成功==", obj)
      if (obj.data.isSuccess == 'T'){
        //保存案件Id
        // wx.setStorageSync("shareCaseId", _this.data.caseId);
        _this.setData({
          checkDiv: false,
          isFocus: false,
          dimNum:0,
          validCodeCheck: false
        });
      }else{
        _this.setData({
          validCodeCheck: true
        });
      }
    }, (obj) => {
      console.log("验证手机号失败=", obj)
    })
  },

  //点击返回首页
  goHome: function(){
    wx.redirectTo({
      url: '../index/index',
    })
  },

  //点击下载文件
  dowmloadFile: function (e) {
    let _this=this;
    let fileurl = e.currentTarget.dataset.url;
    let docName = e.currentTarget.dataset.name;
    let tempSuf = docName.split('.');
    let suffix = tempSuf[tempSuf.length - 1];
    let fileType = "doc,xls,ppt,pdf,docx,xlsx,pptx";
    let picSuffix = "bmp,jpg,png,tiff,gif,pcx,tga,exif,fpx,svg,psd,cdr,pcd,dxf,ufo,eps,ai,raw,WMF,jpeg";
    console.log("fileurl==", fileurl)
    wx.downloadFile({
      url: fileurl, //仅为示例，并非真实的资源
      success: function (res) {
        _this.setData({ isAlredyLoad: true })
        // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
        console.log("读取文件成功=", res)
        // if (res.statusCode === 200) {
        var filePath = res.tempFilePath
        if (fileType.indexOf(suffix) != "-1") {
          wx.openDocument({
            filePath: filePath,
            success: function (res) {
              console.log('打开文档成功')
            }
          })
        } else if (picSuffix.indexOf(suffix.toLowerCase()) != "-1") {
          wx.previewImage({
            current: filePath, // 当前显示图片的http链接
            urls: [filePath] // 需要预览的图片http链接列表
          })
        }
      },
      fail: function (res) {
        console.log("读取文件失败=", res);
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log("此处可以拿到转发的openid=", options.caseId)
    this.setData({
      caseId:options.caseId.split('|')[0],
      nickName: options.caseId.split('|')[1],
    });
  },

  showMore: function () {
    let trackRecordsAll = this.data.trackRecordsAll
    if (trackRecordsAll.length > 3) {
      if (this.data.showMoreTrick) {
        this.setData({
          trackRecords: trackRecordsAll.slice(0, 3),
          showMoreTrick: false
        })
      } else {
        this.setData({
          trackRecords: trackRecordsAll,
          showMoreTrick: true
        })
      }
    }
  },
  //获取openid
  getOpenid: (_that) => {
    console.log("app.globalData.code:" + app.globalData.code);
    if (!app.globalData.userInfo) {
      wx.showLoading({
        title: '加载中',
      })
    }

    request.request_api(app.globalData.code, (data) => {
      console.log("openid成功", data)
      app.globalData.openid = data.data.openid;
      app.globalData.session_key = data.data.session_key;
      try {
        if (data.data.unionid) {
          app.globalData.unionid = data.data.unionid
        } else {
          //开始解析获取Unionid
          let pc = new WXBizDataCrypt(app.globalData.appid, app.globalData.session_key);
          let decodeData = pc.decryptData(app.globalData.encryptedData, app.globalData.iv);
          console.log('解密后 decodeData: ', decodeData);
          app.globalData.unionid = decodeData.unionid
        }
      } catch (e) {
        console.log("抛出异常=", e)
        wx.hideLoading()
        //开始解析获取Unionid
        let pc = new WXBizDataCrypt(app.globalData.appid, app.globalData.session_key);
        let decodeData = pc.decryptData(app.globalData.encryptedData, app.globalData.iv);
        console.log('解密后 decodeData: ', decodeData);
        app.globalData.unionid = decodeData.unionid
      }
      if (!app.globalData.sessionId) {
        _that.loginApi();
      } else {
        _that.getShareCaseInfo();
      }
    }, (data) => {
      wx.hideLoading();
      console.log("openid失败", data)
      wx.showModal({
        title: "加载失败",
        content: '请尝试下拉界面重新加载',
        confirmText: '确定',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
          } else if (res.cancel) {
          }
        }
      })
    });
  },

  //登录调用
  loginApi: function () {
    let headerInfo = {
      pageNum: "",
      pageSize: "",
      sessionId: "",
    }
    let bodyInfo = {
      loginType: "mp",
      thirdLoginId: app.globalData.openid,
      unionid: app.globalData.unionid,
      nickName: app.globalData.userInfo.nickName,
      avatar: app.globalData.userInfo.avatarUrl,
      regChannel: '6'
    }
    let _this = this;
    request.requestLogin_api("userLogin", headerInfo, bodyInfo, (obj) => {
      wx.hideLoading();
      if (obj.data.isSuccess == "F" && obj.data.errorCode == "ERROR_NOT_REG") {
        _this.getLoginInfo(_this);
        // wx.navigateTo({
        //   url: '../reg/reg',
        // })
      } else if (obj.data.isSuccess == "T") {
        console.log("用户登录成功=", obj)
        app.globalData.sessionId = obj.data.sessionId;
        //保存手机号
        app.globalData.mobileNo = JSON.parse(obj.data.body).mobileNo;
        app.globalData.userName = JSON.parse(obj.data.body).userName;
        // if (app.globalData.userName == _this.data.nickName) {
        //   this.setData({
        //     checkDiv: false,
        //     dimNum: 0
        //   });
        // }
        _this.getShareCaseInfo();
      }
    }, (obj) => {
      wx.hideLoading();
      console.log("用户登录失败=", obj)
      wx.showModal({
        title: "加载失败",
        content: '请尝试下拉界面重新加载',
        confirmText: '确定',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
          } else if (res.cancel) {
          }
        }
      })
    })
  },

  // 获取登录信息
  getLoginInfo: (that) => {
    //获取第三方接口登录数据
    let bodyInfo = {
      openid: app.globalData.openid,
      mobileNo: app.globalData.mobileNo,
      unionid: app.globalData.unionid,
      nickName: app.globalData.userInfo.nickName,
      avatarUrl: app.globalData.userInfo.avatarUrl
    };
    let _this = that;
    console.log("bodyInfo====", bodyInfo)
    request.get_api("login", bodyInfo, (res) => {
      wx.hideLoading();
      console.log("获取用户信息成功=", res)
      let bodyData = JSON.parse(res.data.body);
      if (res.data.isSuccess == 'T' && bodyData.memUserInfo.mobileNo) {
        //保存数据
        app.globalData.persionalInfo = bodyData.memUserInfo;
        app.globalData.mobileNo = bodyData.memUserInfo.mobileNo;
        wx.hideShareMenu();
        _this.regErp(_this);
      } else {
        wx.navigateTo({
          url: '../reg/reg',
        })
      }
    }, (res) => {
      wx.hideLoading();
      console.log("获取用户信息失败=", res)
      wx.showModal({
        title: "加载失败",
        content: '请尝试重新加载',
        confirmText: '确定',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
          } else if (res.cancel) {
          }
        }
      })
    });
  },

  // 用户注册
  regErp: function (that) {
    let headerInfo = {
      pageNum: "",
      pageSize: "",
      sessionId: "",
    }
    let bodyInfo = {
      loginType: "mp",
      thirdLoginId: app.globalData.openid,
      unionid: app.globalData.unionid,
      mobileNo: app.globalData.mobileNo,
      nickName: app.globalData.userInfo.nickName,
      avatar: app.globalData.userInfo.avatarUrl,
      regChannel: '6',
      mobileCheckNo: "SUCCESS"
    }
    let _that = that;
    request.requestLogin_api("userLogin", headerInfo, bodyInfo, (res) => {
      wx.hideLoading();
      console.log("注册成功=", res)
      app.globalData.sessionId = res.data.sessionId;
      app.globalData.userName = JSON.parse(res.data.body).userName;
      _that.getShareCaseInfo();
    }, (res) => {
      console.log("注册失败=", res)
      wx.showModal({
        title: "加载失败",
        content: '请尝试重新加载',
        confirmText: '确定',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
          } else if (res.cancel) {
          }
        }
      })
    });
  },


  showFile: function (e) {
    let showfileindex = e.currentTarget.dataset.showfileindex;
    let _trackRecords = this.data.trackRecords
    if (_trackRecords[showfileindex].caseDocBeans.length > 0) {
      _trackRecords[showfileindex].openFile = !_trackRecords[showfileindex].openFile;
      this.setData({ trackRecords: _trackRecords })
    }
  },
  goDetail: function () {
    this.setData({ isAlredyLoad: true })
    wx.navigateTo({
      url: '../caseDetail/caseDetail',
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.toast = this.selectComponent("#toast");
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (this.data.isAlredyLoad) {
      this.setData({ isAlredyLoad: false })
      return
    }
    if (!app.globalData.userInfo) {
      // 获取用户信息
      let _that = this;
      app.getAuthUserInfo((res)=>{
          // 可以将 res 发送给后台解码出 unionId
          res.userInfo.nickName = res.userInfo.nickName.replace(/\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g, "");
          app.globalData.userInfo = res.userInfo;
          app.globalData.encryptedData = res.encryptedData;
          app.globalData.iv = res.iv;
          wx.showLoading({
            title: '加载中',
          })
          _that.getOpenid(_that);
      },(res)=>{
        console.log("获取用户信息失败=", res)
        _that.setData({
          showModel: true
        })
      });
    } else {
      if (!app.globalData.sessionId) {
        this.loginApi();
      } else {
        if (app.globalData.userName == this.data.nickName){
          this.setData({
            checkDiv: false,
            dimNum: 0
          });
        }
        this.getShareCaseInfo();
      }
    } 
  },

  //组件授权回调
  _setAuthorization: function (e) {
    let that = this;
    let res = e.detail;
    that.getOpenid(that);
  },

 //验证手机号
  checkVerifyUserShare: function(){
    let headerInfo = {
      pageNum: "",
      pageSize: "",
      sessionId: app.globalData.sessionId
    }
    let bodyInfo = {
      caseId: this.data.caseId
    }
    let _this = this;
    wx.hideLoading();
    request.requestLogin_api("checkVerifyUserShare", headerInfo, bodyInfo, (obj) => {
      console.log("验证是否需要输手机号成功==", obj)
      let flag = obj.data.body;
      if (app.globalData.userName == _this.data.nickName) {
        this.setData({
          checkDiv: false,
          dimNum: 0
        });
      }else{
        if (flag == 'SUCCESS' || flag == 'pass') {
          _this.setData({
            checkDiv: false,
            dimNum: 0
          });
        }
      }
    }, (obj) => {
      console.log("验证是否输入手机号失败=", obj)
    })
  },


  //获取案件详情接口
  getShareCaseInfo: function(){
    let headerInfo = {
      pageNum: "",
      pageSize: "",
      sessionId: app.globalData.sessionId
    }
    let bodyInfo = {
      caseId: this.data.caseId
    }
    let _this = this;
    wx.hideLoading();
    request.requestLogin_api("queryCaseInfoDetail", headerInfo, bodyInfo, (obj) => {
      let caseInfo = JSON.parse(obj.data.body);
      app.globalData.caseTempData = caseInfo;
      console.log("caseTempData==", caseInfo)
      if (caseInfo.isShareManage == 'Y') {
        _this.setData({
          isShareManage: true,
          shareList: caseInfo.shareList
        });
      }
      // caseInfo.caseAmt = util.filterFormatAmt(caseInfo.caseAmt * 1 / 10000);
      caseInfo.status = util.investStatusFilter(caseInfo.status);
      _this.setData({
        caseInfoData: caseInfo
      });
      _this.queryCaseTrackAndDoc();
    }, (obj) => {
      console.log("查询某个案件的详情失败=", obj)
    })
  },

  queryCaseTrackAndDoc: function () {
    let headerInfo = {
      pageNum: "",
      pageSize: "",
      sessionId: app.globalData.sessionId
    }
    let bodyInfo = {
      caseId: app.globalData.caseTempData.caseId
    }
    let _this = this;
    request.requestLogin_api("queryCaseTrackAndDoc", headerInfo, bodyInfo, (obj) => {
      var res = JSON.parse(obj.data.body), _trackRecords = [], _showMoreBtn = false;
      console.log('queryCaseTrackAndDoc_res', res)
      var arr = res.enforceTrackRecords.concat(res.lawsuitTrackRecords).concat(res.riskTrackRecords);
      console.log('queryCaseTrackAndDoc', arr)
      arr.forEach(function (e) {
        e.dateStr = e.trackRecordBean.operDate.substring(5);
        e.clock = e.trackRecordBean.operTime.substring(0, 5);
        if (e.caseDocBeans.length > 0) {
          e.openFile = true;
        } else {
          e.openFile = false;
        }
        e.caseDocBeans.forEach((item) => {
          item.docUrlStr = item.docUrl.replace(app.globalData.winhc_oss_url, '').replace(app.globalData.old_winhc_oss_url, '').replace(/[A-Z|A-z|2-8]{10}/, '');
        })
      });
      if (arr.length > 3) {
        _trackRecords = arr.slice(0, 3);
        _showMoreBtn = true;
      } else {
        _trackRecords = arr;
        _showMoreBtn = false;
      }
      _this.setData({
        trackRecords: _trackRecords,
        trackRecordsAll: arr,
        showMoreBtn: _showMoreBtn
      });
      _this.checkVerifyUserShare();
    }, (obj) => {
      console.log("查询某个案件的站内信列表失败==", obj)
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // }
})